// 设备定义
<template>
  <div class="item1">
    <div class="title" @click="isShow = !isShow">
      {{$t("basic.equip_list")}}
      <i class="el-icon-caret-bottom zhedie" v-show="isShow"></i>
      <i class="el-icon-caret-top zhedie" v-show="!isShow"></i>
    </div>
    <div class="breadcrumb" :gutter="24" v-show="isShow">
      <el-form ref="form" :model="formData" label-width="90px" size="small">
        <el-row :gutter="28">
          <el-col :xs="3" :sm="1" :md="1" :lg="1" :xl="1">
            <el-button type="primary" size="small" :icon="'iconfont ' + icon" class="change" @click="changePattern"></el-button>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="4" style="padding-top:10px">
            <el-form-item :label="$t('common.keyword')">
              <el-input v-model="formData.keyword" clearable placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="3" :sm="2" :md="2" :lg="2" :xl="2" style="padding-top:10px">
            <el-form-item label-width="0px">
              <el-button type="primary" size="small" @click="handleSearch">{{ $t("common.query") }}</el-button>
            </el-form-item>
          </el-col>
          <div class="btngroup" style="padding-right:15px">
            <el-button type="primary" size="small" @click="handleAdd()">{{ $t("common.add") }}</el-button>
            <el-button type="primary" size="small" @click="handleEdit()">{{ $t("common.edit") }}</el-button>
            <el-button type="primary" size="small" @click="handleDel()">{{ $t("common.remove") }}</el-button>
            <el-button type="primary" size="small" @click="handleCheck()">{{ $t("basic.check_addr") }}</el-button>
          </div>
        </el-row>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="tableAuto" v-show="isShow">
      <el-table :data="tableData" style="width:100%" :height="height" @row-click="rowClick" border stripe
        :header-cell-style="{background:'#EAEBEC'}" v-loading="tableLoading" v-if="!isCard" ref="refTable" highlight-current-row
        :cell-style="statusStyle" @sort-change='sortChange'>
        <el-table-column label="" width="50" align="center">
          <template slot-scope="scope">
            <div>
              <el-radio :label="scope.row.fid" v-model="radioId">&nbsp;</el-radio>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" :label="$t('common.number')" width="90" align="center">
          <template slot-scope="scope">
            {{table_index(scope.$index+1)}}
          </template>
        </el-table-column>
        <el-table-column prop="entName" show-overflow-tooltip :label="$t('basic.entity_name')" width="150"
          sortable='custom'></el-table-column>
        <el-table-column prop="classId" show-overflow-tooltip :label="$t('basic.type_name')" width="140" sortable='custom'>
          <template slot-scope="scope">
            {{scope.row.equipmentClassVo.className}}
          </template>
        </el-table-column>
        <el-table-column prop="entName" show-overflow-tooltip :label="$t('basic.equipment_group')" width="200" sortable='custom'>
          <template slot-scope="scope">
            {{scope.row.trainTxt}}
          </template>
        </el-table-column>
        <el-table-column prop="assetNum" show-overflow-tooltip :label="$t('basic.equipment_number')" width="130"
          sortable='custom'></el-table-column>
        <el-table-column prop="tagAddr" show-overflow-tooltip :label="$t('basic.device_address')" width="130"></el-table-column>
        <el-table-column prop="description" show-overflow-tooltip :label="$t('basic.remarks')"></el-table-column>
      </el-table>
    </div>
    <!-- 卡片区域 -->
    <div v-if="isCard" v-show="isShow">
      <div class="cardBox" style="overflow-x: hidden;border:1px solid #EAEBEC" :style="{height:height} ">
        <el-row :gutter="25">
          <template v-for="(item,index) in tableData">
            <el-col :xs="12" :sm="8" :md="6" :lg="5" :xl="4">
              <div class="card" :key="index" :class="[index == cardIndex ? 'selectCard' : '']" @click="handleIndex(index,item)">
                <p class="time" style="font-weight:bold">{{$t('basic.entity_name')}}：{{item.entName}}</p>
                <div class="time">
                  <el-tooltip :content="item.equipmentClassVo.className" effect="dark" placement="top">
                    <p class="Desc">{{$t('basic.type_name')}}：{{item.equipmentClassVo.className}}</p>
                  </el-tooltip>
                </div>
                <div class="time">
                  <el-tooltip :content="item.trainTxt" effect="dark" placement="top">
                    <p class="Desc">{{$t('basic.equipment_group')}}：{{item.trainTxt}}</p>
                  </el-tooltip>
                </div>
                <div class="time">
                  <el-tooltip :content="item.assetNum" effect="dark" placement="top">
                    <p class="Desc">{{$t('basic.equipment_number')}}：{{item.assetNum}}</p>
                  </el-tooltip>
                </div>
                <div class="time">
                  <el-tooltip :content="item.tagAddr" effect="dark" placement="top">
                    <p class="Desc">{{$t('basic.device_address')}}：{{item.tagAddr}}</p>
                  </el-tooltip>
                </div>
              </div>
            </el-col>
          </template>
          <el-empty description="暂无数据" v-if="tableData.length == 0"></el-empty>
        </el-row>
      </div>
    </div>

    <div class="pagination-area" v-show="isShow">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 30, 50, 100]"
        :page-size="pager.pageSize" :current-page="pager.pageNum" layout="total, sizes, prev, pager, next, jumper" :total="pager.total">
      </el-pagination>
    </div>

    <el-dialog v-dialogDrag :title="title" :visible.sync="isShowDialog" :close-on-click-modal="false"
      :width="screenWidth > 1024 ? '30%' : '50%'" class="isShowDialog" :before-close="handleClose">
      <el-form :model="ruleForm" label-width="85px" ref="ruleForm" size="small" :rules="rules" :hide-required-asterisk="true">
        <el-row :gutter="35">
          <el-col :xs="24">
            <el-form-item :label="$t('basic.entity_name')" prop="entName">
              <el-input v-model="ruleForm.entName" placeholder="" clearable :disabled="inRecipe==1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('basic.type_name')" prop="classId">
              <el-select v-model="ruleForm.classId" remote filterable :remote-method="remoteMethodItemClass" placeholder=""
                v-el-select-loadmore="loadMoreItemClassFun" clearable @clear="clearItemClass" :disabled="inRecipe">
                <el-option v-for="(item,index) in classIdList" :key="index" :label="item.className" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('basic.equipment_group')" prop="trainVos">
              <el-select v-model="ruleForm.trainVos" remote filterable placeholder="" multiple clearable @change="$forceUpdate()"
                :disabled="inRecipe">
                <el-option v-for="(item,index) in deviceGroup" :key="index" :label="item.entName" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('basic.equipment_number')" prop="assetNum">
              <el-input v-model="ruleForm.assetNum" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('basic.device_address')" prop="tagAddr">
              <el-input-number v-model="ruleForm.tagAddr" @change="handleChange" :min="numStart" :max="numEnd"></el-input-number>
              <!-- <el-input-number v-model="ruleForm.tagAddr"></el-input-number> -->
              <!-- <el-select
                          v-model="ruleForm.tagAddr"
                          remote
                          filterable
                          :remote-method="remoteMethodEquipmentAddr"
                          placeholder=""
                          v-el-select-loadmore="loadMoreEquipmentAddrFun"
                          clearable
                          @clear="clearEquipmentAddr"
                      >
                        <el-option v-for="(item,index) in equipmentAddrList" :key="index" :label="item.className" :value="item.fid"></el-option>
                      </el-select> -->
            </el-form-item>
          </el-col>

          <el-col :xs="24">
            <el-form-item :label="$t('basic.remarks')" prop="description">
              <el-input type="textarea" v-model="ruleForm.description" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" v-if="inRecipe==1">
            <el-link type="danger" disabled>设备已经在配方中使用，不能编辑某些字段.</el-link>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleCreateMaterial('ruleForm')"
          :loading="loading">{{ $t("common.preservation") }}</el-button>
        <el-button @click="handleClose()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>

    <el-dialog v-dialogDrag :title="$t('basic.check_addr')" :visible.sync="isShowCheck" :close-on-click-modal="false"
      :width="screenWidth > 1024 ? '30%' : '60%'" :before-close="handleCloseCheck">
      <div style="padding:15px 0;">
        <el-alert v-for="err in errorList" :title="err" :key="err" type="error" show-icon closable=false style="margin-bottom:10px;" />

      </div>

    </el-dialog>

    <drawer :drawer="drawer" @handleClose="handleCloseDrawer" :equipmentClassId="equipmentClassId" :radioId="radioId"
      :screenWidth="screenWidth"></drawer>

  </div>
</template>

<script>
import { configure } from "@/api/configure"
import drawer from "./template/index.vue"
import { siteConfig } from '@/api/siteConfig'
export default {
  components: {
    drawer
  },
  data () {
    return {
      screenWidth: document.body.clientWidth,
      height: 32 * 11.4,
      formData: {
        keyword: "",
      },
      ruleForm: {
        entName: "",
        classId: "",
        trainVos: [],
        assetNum: "",
        tagAddr: "",
        description: "",
        canStore: 0,
        canShip: 0,
        canReceive: 0,
      },
      rules: {
        entName: [{ required: true, message: '实体名称不能为空', trigger: 'blur' }],
        classId: [{ required: true, message: '类型名称不能为空', trigger: 'blur' }],
      },
      isShowDialog: false,
      icon: "icon-biaoge",
      title: "新增物料信息",
      loading: false,
      tableData: [],
      tableLoading: false,
      radioId: "",
      pager: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        field: 'classId,entName',
        order: 'asc'
      },
      pagerClass: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      pagerEquipmentAddr: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },

      classIdList: [],
      equipClassList: [],
      equipmentAddrList: [],
      keywordClassId: "",
      keywordEquipmentAddr: "",
      pagerUom: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      uomIdList: [],
      keywordUomId: "",
      isCard: false,
      cardIndex: -1,
      icon: "icon-biaoge",
      deviceGroup: [],
      curRow: {},
      currObj: {},
      drawer: false,
      equipmentClassId: "", //设备类的id
      isShow: true,
      numEnd: 0,
      numStart: 0,
      unitMax: 1,
      inRecipe: 0,
      isShowCheck: false,
      errorList: [],
    }
  },
  created () {
    this.addrUnitList()
    // this.handleCheck()
    this.getEquipmentClassList()
    // this.getUomList()
    this.getEquipmentList()
    this.getTrainList()
    this.getEquipmentAddrList()

  },
  watch: {
    screenWidth (val) {
      this.screenWidth = Number(val)
    }
  },
  mounted () {
    const that = this

    window.addEventListener('resize', function () {
      that.screenWidth = document.body.offsetWidth;
    })
  },
  methods: {
    handleSearch () {
      this.pager.pageNum = 1;
      this.getEquipmentList()
    },
    getEquipmentList () {
      const param = {
        entName: this.formData.keyword,
        page: this.pager.pageNum,
        size: this.pager.pageSize,
        field: this.pager.field,
        order: this.pager.order,
      }
      this.tableLoading = true
      configure.getEquipmentList(param).then(res => {
        this.tableLoading = false
        if (res.code == 200) {
          this.tableData = res.data.rows
          this.tableData.forEach(item => {
            item.trainTxt = ''
            if (item.trainVos && item.trainVos.length > 0) {
              item.trainVos.forEach((item1, index) => {
                item.trainTxt += index < item.trainVos.length - 1 ? item1.entName + "，" : item1.entName
              })
            }
          })

          this.pager.total = res.data.total
        }
      })
    },
    statusStyle ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 6) {
        // if (this.tableData[rowIndex].tagAddr >= this.unitMax) {
        //   return 'background:#F4B183'
        // }
        // else {
        //   return 'background:#FFFFFF'
        // }
      }
    },
    sortChange (column) {
      if (column.order === 'descending') {
        this.pager.field = column.prop
        this.pager.order = 'DESC'
      } else {
        this.pager.field = column.prop
        this.pager.order = 'ASC'
      }
      this.pager.pageNum = 1
      this.getEquipmentList()
    },
    handleSizeChange (val) {
      this.pager.pageNum = 1
      this.pager.pageSize = val
      this.getEquipmentList()
    },
    handleCurrentChange (val) {
      this.pager.pageNum = val;
      this.getEquipmentList()
    },
    handleClose () {
      this.isShowDialog = false
    },
    handleAdd () {
      this.title = "新增设备定义"
      this.ruleForm = {}
      // this.ruleForm.tagAddr = this.numStart
      // this.ruleForm.trainVo.fid = ''
      this.$set(this.ruleForm, "trainVos", [])
      // this.$set(this.ruleForm.trainVo,"fid",'')
      try {
        this.$refs['ruleForm'].resetFields();
      } catch (e) { }
      this.isShowDialog = true
      this.inRecipe = 0

    },
    async handleEdit () {
      if (this.radioId === '') {
        this.$message.error(this.$t('dialog.please_sel_edit'));
        return
      }
      this.title = "编辑设备定义"
      try {
        let res = await configure.findEquipment(this.radioId)
        if (res.code == 200) {
          this.curRow = res.data

          this.ruleForm = {}
          try {
            this.$refs['ruleForm'].resetFields();
          } catch (e) { }

          this.ruleForm = {
            entName: res.data.entName,
            classId: res.data.classId,
            fid: res.data.fid,
            trainVos: [],
            description: res.data.description,
            assetNum: res.data.assetNum,
          }
          if (res.data.tagAddr != null) {
            this.$set(this.ruleForm, 'tagAddr', res.data.tagAddr)
            // this.ruleForm.tagAddr = res.data.tagAddr
          }
          if (res.data.trainVos && res.data.trainVos.length > 0) {
            this.ruleForm.trainVos = res.data.trainVos.map(item => item.fid)
          }
          const index = this.classIdList.findIndex(item => item.fid == res.data.classId)
          if (index == -1) {
            this.classIdList.push({
              className: res.data.equipmentClassVo ? res.data.equipmentClassVo.className : '',
              fid: res.data.classId
            })
          }
          this.isShowDialog = true
          this.inRecipe = res.data.inRecipe
        }
      } catch (e) {

      }

    },
    handleCreateMaterial (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {

          let equipCls = this.equipClassList.filter(el => el.fid == this.ruleForm.classId)
          this.ruleForm.canStore = equipCls[0].canStore
          this.ruleForm.canShip = equipCls[0].canShip
          this.ruleForm.canReceive = equipCls[0].canReceive

          const param = Object.assign({}, this.ruleForm)
          param.trainVos = this.ruleForm.trainVos.map(item => {
            return {
              fid: item
            }
          })
          this.loading = true
          configure.equipmentAdd(param, this.title).then(res => {
            this.loading = false
            if (res.code == 200) {
              this.$refs[formName].resetFields();
              this.getEquipmentList()
              this.isShowDialog = false
            } else {
              this.$message.error(res.msg);
            }
          }).catch(e => {
            this.loading = false
          })
        } else {
          return false
        }
      })
    },
    async handleDel () {
      if (this.radioId === '') {
        this.$message.error(this.$t('dialog.please_sel_del'));
        return
      }
      try {
        let res = await configure.findEquipment(this.radioId)
        let that = this

        if (res.code == 200) {
          that.$customConfirm({
            content: "请确认是否删除实体名称" + this.currObj.entName,
            onok () {
              configure.removeEquipmentDev(res.data.fid).then(res1 => {

                if (res1.code == 200) {
                  that.radioId = ""
                  that.cardIndex = -1
                  that.getEquipmentList()
                  that.$message({ duration: 1000, type: 'success', message: '删除成功!' });
                } else {
                  that.$message.error(res1.msg);
                }
              })
            }
          });
        } else {
          this.$message.error(res.msg);
        }
      } catch (e) {

      }
    },

    async handleCheck () {
      configure.checkEquip().then(res => {
        if (res.code == 200) {
          this.errorList = res.data
          if (res.data.length == 0) {
            // this.isShowCheck = false
            this.$message({ duration: 1000, type: 'success', message: '配方检验成功!' })
          } else {
            this.isShowCheck = true
          }
        }
      })
    },
    rowClick (row) {
      this.radioId = row.fid;
      this.currObj = row;
      this.equipmentClassId = row.equipmentClassVo ? row.equipmentClassVo.fid : ''
      this.drawer = true
      this.$refs.refTable.setCurrentRow(row);
    },
    handleIndex (index, row) {
      this.cardIndex = index
      this.radioId = row.fid;
      this.drawer = true
    },
    //获取设备定义列表
    getEquipmentClassList () {
      const param = {
        className: this.keywordClassId,
        page: 1,
        size: 999
      }
      configure.getEquipmentClassList(param).then(res => {
        if (res.code == 200) {
          this.equipClassList = res.data.rows

          if (this.curRow.classId) {
            for (let i = 0; i < res.data.rows.length; i++) {
              if (this.curRow.classId == res.data.rows[i].fid) {
                res.data.rows.splice(i, 1)
                break
              }
            }
          }
          this.classIdList = [...this.classIdList, ...res.data.rows]
        }
      }).catch(e => {

      })
    },
    //下拉加载更多设备定义
    loadMoreItemClassFun () {
      // this.pagerClass.pageNum++
      // this.getEquipmentClassList()
    },
    //远程搜索设备定义
    remoteMethodItemClass (keyword) {
      this.keywordClassId = keyword.trim();
      this.pagerClass.pageNum = 1
      setTimeout(() => {
        this.classIdList = []
        this.getEquipmentClassList()
      }, 200)
    },
    clearItemClass () {
      this.keywordClassId = ""
      this.pagerClass.pageNum = 1
      this.classIdList = []
      this.getEquipmentClassList()
    },
    //获取设备定义列表
    getEquipmentAddrList () {
      const param = {
        className: this.keywordEquipmentAddr,
        page: this.pagerEquipmentAddr.pageNum,
        size: this.pagerEquipmentAddr.pageSize
      }
      configure.getEquipmentClassList(param).then(res => {
        if (res.code == 200) {
          if (this.curRow.classId) {
            for (let i = 0; i < res.data.rows.length; i++) {
              if (this.curRow.classId == res.data.rows[i].fid) {
                res.data.rows.splice(i, 1)
                break
              }
            }
          }
          this.equipmentAddrList = [...this.equipmentAddrList, ...res.data.rows]
          console.log(this.equipmentAddrList);
        }
      }).catch(e => {

      })
    },
    //下拉加载更多设备定义
    // loadMoreEquipmentAddrFun(){
    //     this.pagerEquipmentAddr.pageNum ++
    //     this.getEquipmentAddrList()
    // },
    // //远程搜索设备定义
    // remoteMethodEquipmentAddr(keyword){
    //     this.keywordEquipmentAddr = keyword.trim();
    //     this.pagerEquipmentAddr.pageNum = 1
    //     setTimeout(() => {
    //         this.equipmentAddrList = []
    //         this.getEquipmentAddrList()
    //     },200)
    // },
    // clearEquipmentAddr(){
    //     this.keywordEquipmentAddr = ""
    //     this.pagerEquipmentAddr.pageNum = 1
    //     this.equipmentAddrList = []
    //     this.getEquipmentAddrList()
    // },


    changePattern () {
      this.isCard = !this.isCard
      this.radioId = ''
      this.cardIndex = -1
      this.icon = this.isCard ? 'icon-qiehuan' : 'icon-biaoge'
    },
    table_index (index) {
      return (this.pager.pageNum - 1) * this.pager.pageSize + index
    },
    //获取设备组
    getTrainList () {
      const param = {
        entName: ''
      }
      configure.getTrainList(param).then(res => {
        if (res.code == 200) {
          this.deviceGroup = res.data.rows
        }
      })
    },
    handleCloseDrawer () {
      this.drawer = false
    },
    addrUnitList () {
      configure.addrUnitList().then(res => {
        if (res.code == 200) {
          this.numStart = res.data.rows[0].numStart
          this.numEnd = res.data.rows[0].numEnd
          // this.$set(this.ruleForm, 'tagAddr', res.data.rows[0].numStart)
        }
      })
    },
    handleChange (val) {
      this.$forceUpdate()
    }
  }
}
</script>

<style scoped>
.btngroup {
  float: right;
}
.change >>> .iconfont {
  font-size: 13px !important;
}
.titmepicker >>> .el-date-editor {
  width: 100%;
}
.titmepicker >>> .el-date-editor .el-range-separator {
  width: 8%;
}
.isShowDialog >>> .el-select {
  width: 100%;
}
.tableAuto,
.cardBox {
  clear: both;
}
.pagination-area {
  padding: 10px;
  border: 1px solid #eaebec;
  border-top: none;
}
.Desc {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.cardBox {
  overflow-y: auto;
}
.card {
  background: #eaebec;
  margin-bottom: 20px;
  padding: 10px;
  border-radius: 3px;
}
.card p {
  font-size: 12px;
  line-height: 22px;
  transform: scale(0.9);
}
.desc {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.descAlarm {
  background: #f4b183;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.title {
  font-weight: bold;
}
.selectCard {
  background: #f6fbff;
}
@media only screen and (min-width: 1200px) {
  .el-col-lg-5 {
    width: 19.83333%;
  }
}
.item1 >>> .el-row {
  margin: 0 !important;
}
.title {
  line-height: 35px;
  background: #3b2e58;
  color: #fff;
  padding: 0 15px;
  font-size: 14px;
  margin-top: 10px;
  cursor: pointer;
}
.zhedie {
  float: right;
  line-height: 35px;
  font-size: 18px;
  cursor: pointer;
}
</style>